package com.l.web.master.system.user;

import com.l.web.master.system.role.Role;
import com.l.web.master.system.role.RoleDAO;
import org.l.qiao.Cluster;
import org.l.qiao.Page;
import org.l.qiao.search.Field;
import org.l.qiao.search.Query;
import org.l.qiao.web.KeyUpdate;
import org.l.qiao.web.ResponseCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserDAO userDAO;
    @Autowired
    private RoleDAO roleDAO;

    public UserService() {
    }

    public Cluster getPageList(Page page) {
        Field field = new Field();
        Query query = new Query();
        field.include(User.NAME, User.CREATED);
        Cluster userPage = userDAO.findPage(query, field, null, page);
        return userPage;
    }

    public Cluster getRoleMap() {
        List<Cluster> roleList = roleDAO.find(null, new Field(Role.NAME), null);
        Cluster roles = new Cluster();
        for (Cluster role : roleList) {
            roles.put(role.getId(), role.get(Role.NAME));
        }
        return roles;
    }

    public User getDetail(String id) {
        Cluster cluster = userDAO.findById(id);
        return new User(cluster);
    }

    public Cluster getRoleMap(User user) {
        Cluster role = new Cluster();

        if (user.containsKey(User.ROLE_ID)) {
            String rid = user.getString(User.ROLE_ID, "");
            role = roleDAO.findById(rid);
        }

        return role;
    }

    public long getCount(String userName) {
        Query query = new Query();
        query.eq(User.USER_NAME, userName);
        long count = userDAO.count(query);
        return count;
    }

    public int save(User user) {
        int result;
        long count = getCount(user.getString(User.USER_NAME, null));

        if (count > 0) {
            result = ResponseCode.REPEAT;
        } else {
            String id = user.setId();
            user.put(User.CREATED, new Date());
            userDAO.insert(user);
            result = ResponseCode.FINISH;
        }
        return result;
    }

    public List<Cluster> getRoles() {
        Field field = new Field();
        field.include(Role.ID, Role.NAME, Role.PARENT_ID);
        List<Cluster> roles = roleDAO.find(null, field, null);
        return roles;
    }

    public int update(KeyUpdate keyUpdate) throws Exception {
        int result;
        result = userDAO.update(keyUpdate);
        return result;
    }

    public int remove(List<String> ids) {
        Query query = new Query();
        query.idIn(ids);
        userDAO.remove(query);
        return ResponseCode.FINISH;
    }
}
